package com.epoint.pjq.core.mqtt;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;

/**
 * 
 * @author lilin
 * @date 2016年9月14日 上午9:34:01
 * @annotation MQTT Service
 */

public class SMP_MQTT_Service extends Service {
	
	// 广播接收器：收到的用户消息
	public static final String ACTION_INTENT_RECEIVER_USERINFO = "SMP_MQTTConnection_UserInfo";
	// 广播接收器：MQTT日志记录
	public static final String ACTION_INTENT_RECEIVER_LOG 	   = "SMP_MQTTConnectionTest_Activity_LOG_Receiver";
	
	public static Context mContext;
	public static SMP_MQTT_Service instance;
	public static boolean isStarted;
	
	private PowerManager.WakeLock wakeLock;
	
	public static String topic;
	public static String keepalivetime;
	public static String hosturi;
	
	public static synchronized void initializeInstance(SMP_MQTT_Service mService) {
		if (instance == null)
			instance = mService;
	}

	public static synchronized SMP_MQTT_Service getInstance() {
		if (instance == null)
			throw new IllegalStateException();
		else
			return instance;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		// 初始化一个单例
		initializeInstance(this);
		
		// 禁止休眠
		acquireWakeLock();
		
		SMP_MQTT_Bizlogic.sendLogBroadcast("MQTT服务已启动");
		
		// 全局上下文
		mContext			= this;
		isStarted 			= true;
		
		topic 			= intent.getStringExtra("topic");
		hosturi 		= intent.getStringExtra("hosturi");
		keepalivetime 	= intent.getStringExtra("keepalivetime");
		
		// 启动MQTT连接线程
		new SMP_MQTT_ConnectionThread().start();
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	

	/** 开启MQTT监控服务 **/
	public static void startMqttService(Context con,String topic,String hosturi,String keepalivetime)
	{
		Intent intent = new Intent(con, SMP_MQTT_Service.class);
		intent.putExtra("topic"			, topic);
		intent.putExtra("hosturi"		, hosturi);
		intent.putExtra("keepalivetime"	, keepalivetime);
		con.startService(intent);
	}
	
	/** 销毁MQTT监控服务 **/
	public static void stopMqttService(Context con)
	{
		Intent intent = new Intent(con, SMP_MQTT_Service.class);
		con.stopService(intent);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		wakeLock.release();
		
		isStarted = false;
		
		SMP_MQTT_Bizlogic.sendLogBroadcast("MQTTService:onDestroy");
		SMP_MQTT_EpointClient.getInstance().destory();
	}
	
	/** 获得休眠锁 禁止系统休眠 **/
	private void acquireWakeLock()
	{
		PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, getPackageName()+"/"+this.getClass().getName());
		wakeLock.acquire();
	}
}
